﻿var IsAddNew = false;

$(document).ready(function () {
    $("#btnAddNew").click(function () {
        $("#divBarSearch, #divListItem").css("display", "none");
        $("#divAddNew").css("display", "");
        IsAddNew = true;
        $("#trAddNew").css("display", "none");
    });
    $("#btnEdit").click(function () {
        $("#divBarSearch, #divListItem").css("display", "");
        $("#divAddNew").css("display", "none");
    });

    //    $('#file_upload').uploadify({
    //        'uploader': 'Images/uploadify.swf',
    //        'script': 'FileHandler.ashx',
    //        'cancelImg': 'Images/cancel.png',
    //        'folder': '../Images/Flowers',
    //        'multi': true,
    //        'fileDataName': 'Filedata',
    //        //'scriptData': { 'name': $("input[id$='txtName']").val(), 'desc': $("input[id$='txtDesc']").val(), 'maincate': $("select[id$='ddlCategory']").val(), 'subcate': $("select[id$='ddlSubcate']").val(), 'showhome': $("input[id$='ckbIsShowHomePage']").attr("checked"), 'showown': $("input[id$='ckbShowOwnPage']").attr("checked") },
    //        'onComplete': function (event, ID, fileObj, response, data) {
    //            
    //            $("span[id$='spResult']").text("Successful");
    //        },
    //        'onProgress': function (event, ID, fileObj, data) {
    //            $("span[id$='spResult']").text("Loading ... ");
    //            
    //        },
    //        'onError': function (event, ID, fileObj, errorObj) {
    //            //alert(errorObj);
    //            $("span[id$='spResult']").text(errorObj);
    //            UploadError();
    //        }
    //    });

    $('#file_upload').uploadify({
        'uploader': 'Images/uploadify.swf',
        'script': 'FileHandler.ashx',
        'cancelImg': 'Images/cancel.png',
        'folder': '../Images/Flowers',
        'buttonText': 'Browse',
        'multi': true,
        'fileDataName': 'Filedata',
        'fileExt': '*.jpg;*.gif;*.png;*.bmp',
        'fileDesc': 'Web Image Files (.JPG, .PNG, .BMP, .JPEG, .TIFF)',
        //'sizeLimit': 1048576,
        'onSelect': function (event, ID, fileObj) {

        },
        'onProgress': function (event, ID, fileObj, data) {
            $("span[id$='spResult']").text("Loading ... ");
        },
        'onComplete': function (event, ID, fileObj, response, data) {
            var curTargetID = event.target.id;
            $("span[id$='spResult']").text("Insert thành công rồi đấy mày");
        },
        'onError': function (event, ID, fileObj, errorObj) {
            $("span[id$='spResult']").text("Có lỗi rồi mày ơi: " + errorObj.message);
            //$("span[id$='spResult']").text("Có lỗi rồi mày ơi. Thử lại xem sao");
            //UploadError();
        }
    });

    $("#btnSaveImage").click(function () {
        startUpload();
        $("#file_upload").uploadifyUpload();
    });

    $("select[id$='ddlCate']").change(function () {
        var iCateId = $("select[id$='ddlCate'] option:selected").val();
        GetSubMenu(iCateId);
    });

    $("select[id$='ddlCategory']").change(function () {
        var iCateIdAdd = $("select[id$='ddlCategory'] option:selected").val();
        GetSubMenu(iCateIdAdd);
    });

    //For insert to Product
    $("select[id$='ddlSubcate']").change(function () {
        var iSubCate = $("select[id$='ddlSubcate'] option:selected").val();
        if (parseInt(iSubCate) === 1) {
            $("select[id$='ddProduct']").attr("disabled", "disabled");
        }
        else {
            GetProductByCate();
            $("select[id$='ddProduct']").removeAttr("disabled");
        }

    });

    //For update images
    $("input[id$='btnUpdateImg']").click(function () {
        var lstImg = new Array();
        $("tr", $("table[id$='grvImg']")).each(function (index) {
            if (index > 0) {
                CImage = {
                    Id: $("img[id$='imgItem']", $(this)).attr("alt"),
                    Name: $("input[id$='txtName']", $(this)).val(),
                    Description: $("input[id$='txtDesc']", $(this)).val(),
                    IsShowHome: ($("input[id$='ckShowHome']", $(this)).is(':checked') == true ? "1" : "0"),
                    IsShowOwn: ($("input[id$='ckShowOwn']", $(this)).is(':checked') == true ? "1" : "0"),
                    IsActive: ($("input[id$='ckActive']", $(this)).is(':checked') == true ? "1" : "0"),
                    IsDelete: ($("input[id$='ckDelete']", $(this)).is(':checked') == true ? "1" : "0"),
                    ImgOrder: $("input[id$='txtOrder']", $(this)).val()
                };
                lstImg.push(CImage);
            }
        });


        $.ajax({
            url: "Images.aspx/UpdateImg",
            type: "POST",
            data: JSON.stringify({ 'lstImg': lstImg }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) { UpdateImageSucc(data); },
            error: function () { }
        });

    });
    //Set dropdownlist change
    $("select[id$='ddlCate']").change();

});

function startUpload() {
    var IsShowHomePage=false;
    var IsShowOwn = false;
    var IsActive = false;
    var IsDelete = false;
    if ($("input[id$='ckbIsShowHomePage']").is(':checked')) {
        IsShowHomePage = true;
    }
    if ($("input[id$='ckbShowOwnPage']").is(':checked')) {
        IsShowOwn = true;
    }
    if ($("input[id$='ckbActive']").length === 1)
        IsActive = $("input[id$='ckbActive']").is(':checked');

//    if ($("input[id$='ckbDelete']").length === 1)
//        IsDelete = $("input[id$='ckbActive']").is(':checked');

    //$('#file_upload').uploadifySettings('scriptData', 'name=' + $("input[id$='txtName']").val() + '&amp;desc=' + $("input[id$='txtDesc']").val() + '&amp;maincate=' + $("select[id$='ddlCategory']").val() + '&amp;subcate=' + $("select[id$='ddlSubcate']").val() + '&amp;showhomepage=' + $("input[id$='ckbIsShowHomePage']").attr("checked") + '&amp;showownpage=' + $("input[id$='ckbShowOwnPage']").attr("checked"));


    $('#file_upload').uploadifySettings('scriptData', { 'name': $("input[id$='txtName']").val(), 'desc': $("textarea[id$='txtDesc']").val(), 'maincate': $("select[id$='ddlCategory'] option:selected").val(), 'subcate': $("select[id$='ddlSubcate'] option:selected").val(), 'productid': $("select[id$='ddProduct'] option:selected").val(), 'showhomepage': IsShowHomePage, 'showownpage': IsShowOwn, 'IsActive': IsActive, 'IsDelete': IsDelete });
}

function ShowAllImage() {
    $("span[id$='spResult']").text("Được rồi, Insert thành công rồi đấy mày.");
}

function UploadError() {
    $("span[id$='spResult']").text("Ui cha, có vấn đề rồi , chưa insert được đâu mày.");
}

function GetSubMenu(CateId) {
    $.ajax({
        url: "Images.aspx/GetSubCate",
        type: "POST",
        data: "{CateId:" + CateId + "}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) { GetSubMenu_Complete(data); },
        error: function () { }
    });
}

function GetSubMenu_Complete(data) {
    var sRes = JSON.parse(data.d);
    var List = sRes.lst;
    if (List !== null) {
        var iLen = parseInt(List.length);
        $("select[id$='subCate'] option, select[id$='ddlSubcate'] option").remove();
        for (i = 0; i < iLen; i++) {
            $("select[id$='subCate'], select[id$='ddlSubcate']").append($('<option>').text(List[i].Name).val(List[i].CateId));
        }

        $("select[id$='subCate'], select[id$='ddlSubcate']").prepend($('<option>').text("-- Please Chosse -- ").val("-1")).val("-1");
        $("select[id$='ddlSubcate']").removeAttr("disabled");
        $("select[id$='subCate']").removeAttr("disabled");

    }
    else {
        $("select[id$='ddlSubcate'] option").remove();
        $("select[id$='ddlSubcate']").attr("disabled", true);
        $("select[id$='ddProduct'] option").remove();
        $("select[id$='ddProduct']").attr("disabled", true);

        //For Edit
        $("select[id$='subCate'] option").remove();
        $("select[id$='subCate']").attr("disabled", true);
        $("select[id$='ddProduct'] option").remove();
        $("select[id$='ddProduct']").attr("disabled", true);
    }
}

function GetProductByCate() {
    var iMainCateId = $("select[id$='ddlCategory'] option:selected").val();
    var iSubCateId = $("select[id$='ddlSubcate'] option:selected").val();

    $.ajax({
        url: "Images.aspx/GetProductByCate",
        type: "POST",
        data: "{MainCate:" + iMainCateId + ",SubCate:" + iSubCateId + "}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) { GetProductByCate_Complete(data); },
        error: function () { }
    });
}

function GetProductByCate_Complete(data) {
    var sRes = JSON.parse(data.d);
    var List = sRes.Lst;
    var iLen = parseInt(List.length);
    if (parseInt(iLen) > 0) {
        $("select[id$='ddProduct'] option").remove();
        for (i = 0; i < iLen; i++) {
            $("select[id$='ddProduct']").append($('<option>').text(List[i].Name).val(List[i].Id));
        }

        $("select[id$='ddProduct']").prepend($('<option>').text("-- Please Chosse -- ").val("-1")).val("-1");
    }
}

function UpdateImageSucc(data) {
    if (data.d == 'true') {
        alert("Update thành công rồi, vui quá.");
        $("#btnSubmitCate").click();
    }
    else
        alert("Haiza. Update lỗi rồi");
}

function ShowUpdButton() {
    $("#btnUpdateImg").css("display", "");
}

function HiddenUpdButton() {
    $("#btnUpdateImg").css("display", "none");
}